package cn.hdufocus.focus_helper.service.impl;

import cn.hdufocus.focus_helper.bean.MailBean;
import cn.hdufocus.focus_helper.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImpl implements IMailService {
    private final String tempPath = new ApplicationHome(this.getClass()).getSource().getParentFile().getPath() + "/file/";
    @Autowired
    private JavaMailSender mailSender;

    @Override
    @Async
    public void sendSimpleMail(MailBean mailBean) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //邮件发送人
            simpleMailMessage.setFrom(mailBean.getSender());
            //邮件接收人
            simpleMailMessage.setTo(mailBean.getRecipient());
            //邮件主题
            simpleMailMessage.setSubject(mailBean.getSubject());
            //邮件内容
            simpleMailMessage.setText(mailBean.getContent());
            mailSender.send(simpleMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Async
    public void sendAttachmentsMail(MailBean mailBean, String fileName) {
        String filePath = tempPath + fileName;
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailBean.getSender());
            helper.setTo(mailBean.getRecipient());
            helper.setSubject(mailBean.getSubject());
            helper.setText(mailBean.getContent());
            FileSystemResource file = new FileSystemResource(filePath);
            helper.addAttachment(filePath.substring(filePath.lastIndexOf(File.separator)), file);
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
